<template>
  <a-modal
    :visible="visible"
    :title="$t('all.autotext1089')"
    width="50%"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 10 }"
      labelAlign="left"
    >
      <a-form-model-item
        :label="$t('all.autotext1505')"
        prop="studyAmount"
        v-if="serviceCharge"
      >
        <a-input
          v-model="form.studyAmount"
          :placeholder="$t('all.autotext1201')"
          :min="0.01"
          :precision="2"
          :maxLength="12"
          @input="
            (e) =>
              (this.form.studyAmount = $options.filters.amountCheck(
                e.target.value
              ))
          "
          style="width: 90%"
        />
      </a-form-model-item>
      <a-form-model-item
        :label="$t('all.autotext726')"
        prop="serverAmount"
        v-if="serviceCharge"
      >
        <a-input
          v-model="form.serverAmount"
          :placeholder="$t('all.autotext219')"
          :min="0.01"
          :precision="2"
          :maxLength="12"
          @input="
            (e) =>
              (this.form.serverAmount = $options.filters.amountCheck(
                e.target.value
              ))
          "
          style="width: 90%"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext43')" v-if="serviceCharge">
        <span style="font-size: 24px">{{ count || '0.00' }}</span>
        {{ $t('all.autotext811') }}
      </a-form-model-item>
      <!-- 正式项目uat项目都显示 -->
      <div class="tip" >
        <span v-if="$store.state.user.project?.advancedPay === 1"
          >提示：当前垫付项目可分配金额为</span
        >
        <span v-else>{{ $t('all.autotext1756') }}</span>

        {{ originData || 0 }}{{ $t('all.autotext811') }}
      </div>

      <a-form-model-item
        :label="$t('all.autotext1376')"
        prop="budgetAmount"
        v-if="!serviceCharge"
      >
        <a-input
          v-model="form.budgetAmount"
          :placeholder="$t('all.autotext1201')"
          :min="0.01"
          :precision="2"
          :maxLength="12"
          @input="
            (e) =>
              (this.form.budgetAmount = $options.filters.amountCheck(
                e.target.value
              ))
          "
          style="width: 90%"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext3')" prop="payTime">
        <a-date-picker
          v-model="form.payTime"
          :placeholder="$t('all.autotext763')"
          :format="'YYYY-MM-DD'"
          :valueFormat="'YYYY-MM-DD'"
          style="width: 90%"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext944')" prop="payNo">
        <a-input
          v-model="form.payNo"
          :placeholder="$t('all.autotext375')"
          :maxLength="32"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext441')" prop="proofUrl">
        <div class="clearfix">
          <span>{{ $t('all.autotext276') }}：PNG/JPG</span>
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :beforeUpload="beforeUpload"
            :customRequest="handleCustom"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                {{ $t('all.autotext101') }}
              </div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="previewVisible = false"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-model-item>
      <a-button :loading="btnLoading" type="primary" @click="submit">{{
        $t('all.autotext218')
      }}</a-button>
    </a-form-model>
  </a-modal>
</template>
<script>
import { uploadFile } from '@/api/common'
import { detailForAdjust } from '@/api/overview/budget'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  props: {
    serviceCharge: {
      default: 0 // type = boolean 提示类型错误
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      advancedPay: 0,
      proId: '',
      btnLoading: false,
      form: {
        studyAmount: '',
        serverAmount: '',
        budgetAmount: '',
        payTime: '',
        payNo: '',
        proofUrl: ''
      },
      rules: {
        studyAmount: [
          { required: true, validator: this.moneyValidate, trigger: 'blur' }
        ],
        serverAmount: [
          { required: true, validator: this.moneyValidate, trigger: 'blur' }
        ],
        budgetAmount: [
          { required: true, validator: this.moneyValidate, trigger: 'blur' }
        ]
      },
      fileList: [],
      stopUpload: false,
      previewVisible: false,
      previewImage: '',
      originData: ''
    }
  },
  watch: {
    visible(e) {
      this.advancedPay = sessionStorage.getItem('advancedPay') || 0
      if (!e) {
        this.form = {
          studyAmount: '',
          serverAmount: '',
          budgetAmount: '',
          payTime: '',
          payNo: '',
          proofUrl: ''
        }
        this.fileList = []
        this.$refs.ruleForm.resetFields()
      } else {
        this.detailForAdjust()
      }
    }
  },

  computed: {
    count() {
      return (
        Number(this.form.studyAmount) + Number(this.form.serverAmount)
      ).toFixed(2)
    }
  },
  methods: {
    // 获取弹框默认值
    async detailForAdjust() {
      const res = await detailForAdjust({
        proId: localStorage.getItem('CURRENT_PROID')
      })
      this.originData = res.distributableAmount
    },
    moneyValidate(rule, value, callback) {
      if (!value || +value <= 0) {
        callback(new Error('申报金额需大于0')) // eslint-disable-line
        return
      }
      callback()
    },
    submit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          this.$emit('ok', this.form)
        }
      })
    },
    handleCustom(file) {
      if (this.stopUpload) {
        this.fileList = []
        return
      }
      const params = new FormData()
      params.append('file', file.file)
      uploadFile(params)
        .then((res) => {
          this.form.proofUrl = res
          file.onSuccess(res, file.file)
        })
        .catch(() => {
          this.fileList = []
          this.$message.error(this.$t('all.autotext1259'))
        })
        .finally(() => {})
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 校验图片格式是否符合要求
    beforeUpload(file) {
      const typeVal =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png'
      if (!typeVal) {
        this.$message.error(this.$t('all.autotext559'))
        this.stopUpload = true
      } else {
        this.stopUpload = false
      }
      return typeVal
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    handleCancel() {
      this.$emit('handleCancel')
    }
  }
}
</script>
<style lang="less" scoped>
.tip {
  margin-bottom: 20px;
}
</style>
